//---------------------------------------------------------------------
// File: FileCreateStep.cs
// 
// Summary: 
//
//---------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//---------------------------------------------------------------------

namespace Microsoft.Services.BizTalkApplicationFramework.BizUnit
{
	using System.IO;
	using System.Xml;

	/// <summary>
	/// The FileCreateStep creates a new FILE in the specified directory.
	/// </summary>
	/// 
	/// <remarks>
	/// The following shows an example of the Xml representation of this test step.
	/// 
	/// <code escaped="true">
	///	<TestStep assemblyPath="" typeName="Microsoft.Services.BizTalkApplicationFramework.BizUnit.FileCreateStep">
	///		<SourcePath>.\TestData\InDoc1.xml</SourcePath>
	///		<CreationPath>.\Rec_01\InDoc1.xml</CreationPath>
	///	</TestStep>
	///	</code>
	///	
	///	<list type="table">
	///		<listheader>
	///			<term>Tag</term>
	///			<description>Description</description>
	///		</listheader>
	///		<item>
	///			<term>SourcePath</term>
	///			<description>The location of the input FILE to be copied to the CreationPath</description>
	///		</item>
	///		<item>
	///			<term>CreationPath</term>
	///			<description>The location of the destination FILE</description>
	///		</item>
	///	</list>
	///	</remarks>

	public class FileCreateStep : ITestStep
	{
		/// <summary>
		/// ITestStep.Execute() implementation
		/// </summary>
		/// <param name='testConfig'>The Xml fragment containing the configuration for this test step</param>
		/// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
		public void Execute(XmlNode testConfig, Context context)
		{
			FileStream dstFs = null;
			FileStream srcFs = null;

			try
			{
				string sourcePath = context.ReadConfigAsString( testConfig, "SourcePath" );
				string creationPath = context.ReadConfigAsString( testConfig, "CreationPath" );

				context.LogInfo("FileCreateStep about to copy the data from File: {0} to the File: {1}", sourcePath, creationPath);

				dstFs = File.Create(creationPath);
				srcFs = File.Open(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read);
				byte[] buff = new byte[4096];

				int read = srcFs.Read(buff, 0, 4096);

				while( read > 0 )
				{
					dstFs.Write(buff, 0, read);
					read = srcFs.Read(buff, 0, 4096);
				}
			}
			finally
			{
				if ( null != srcFs )
				{
					srcFs.Close();
				}

				if ( null != dstFs )
				{
					dstFs.Close();
				}
			}
		}
	}
}
